import axios from 'axios'
// import store from '../store'
// import router from '../router'
import { Message, MessageBox } from 'element-ui'
import { route_origins } from '@/api/routes'
// import { overdueLogin } from '@/api/login'
// import { getToken } from '@/utils/auth'
// 创建axios实例
console.log(process.env.BASE_API)
const service = axios.create({
//   baseURL: process.env.BASE_API, // api的base_url
  baseURL: route_origins,
  timeout: 15000 // 请求超时时间
})

const _origin = {
    transformRequest: service.defaults.transformRequest
}

console.log('service.defaults:', service.defaults)
service.defaults.withCredentials = false
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

service.defaults.transformRequest = [function(data) {
    let ret = ''
    for (const it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
}]

service.filterPostData = postData => {
    const posts = {}
    for (const m in postData) {
        if (postData[m] || postData[m] === 0) {
            posts[m] = postData[m]
        }
    }
    return posts
}

// request拦截器
service.interceptors.request.use(config => {
    // config['Content-Type'] = 'application/json;charset=UTF-8'
    console.log('config:', config)
    /*
    if (config.url.match(/127\.0\.0\.1|localhost/img)) {
        config.withCredentials = false
        config.method = 'get'
        config.url += '.json?ajax'
        return config
    }
    if (config.url.match(/http\:\/\/yapi/img)) {
        config.withCredentials = false
    }
    */
    /////// config.url += '?ajax'

    // if (store.getters.token) {
    //     // config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

let isValidLogin = false
let isValidLogin100 = false
window.loginErrStatus = false
const msgPopUp = response => {
    // this.$confirm(`${response.msg}或登录过期, 请重新登录！`, response.msg, {
    //     cancelButtonText: '取消',
    let _c = 0
    const _v = setInterval(t => {
        _c += 100
        const errMsg = document.querySelectorAll('.el-message--error')
        const buttons = document.querySelector('.el-message-box__btns')
        errMsg && errMsg.forEach((m, i) => {
            m.style.display = 'none'
        })
        buttons && buttons.querySelectorAll('button').forEach((m, i) => {
            if (i > 1) {
                buttons.removeChild(m)
            }
        })
        if (_c % 1000 === 0) {
            clearInterval(_v)
            _c = 0
        }
    }, 100)
    if (isValidLogin100) return
    response.msg = response.code === -100 ? '登录失效' : response.msg
    const domLoginErr = document.querySelector('.err-tip') || {
        style: {}
    }
    if (response.code > 100000) {
        window.loginErrStatus = true
        console.warn('Login name, password, valiCode Error :', response)
        // console.log(document.querySelectorAll('.el-form-item__content')[2])
        domLoginErr.innerHTML = response.msg
        domLoginErr.style.display = 'block'
        return
    }
    domLoginErr.style.display = 'none'
    setTimeout(t => {
        MessageBox.alert(`${response.msg}或登录过期, 请重新登录！`, response.msg, {
            confirmButtonText: '确定',
            type: 'warning',
            center: true
        }).then(() => {
            store.dispatch('LogOut').then(() => {
                console.warn('Logout')
                isValidLogin100 = false
                // router.push({
                //     path: router.options.routes[0].path
                // })
            })
        }).catch(() => {})
    }, 500)
    isValidLogin100 = true
}

/**
 *
 * @fileOverview [respone拦截器]
 * @const
 * @param {Number} [code === -1]              [常用接口服务错误]
 * @param {Number} [code === -100]            [登录失效或出错]
 * @param {Number} [code === 204]             [约定为接口正常无数据的情况]
 * @param {Number} [code === 205]             [无权限]
 * @param {Number} [commonCase全0]                  [灰圈：无报表数据]
 * @param {Number} [commonCase部分为0]               [为0数据不显示（包括legend）]
 * @param {Binary} [N/A]                            [无状态码，交给业务端处理]
 * @param {Number} [code !== (-100|-1|200)]   [返回res原对象交给具体业务内自定义处理（包括204）]
 *
 */
let isAborted = false
service.interceptors.response.use(
    response => {
        const res = response.data
        console.log('request-response:', response)
        // if (res.code) {
        if (res.result === 'ok') {
            window.loginErrStatus = false
            if (res.code > 100000) {
                if (res.code > 200000) {
                    return res
                }
                isAborted = true
                // document.querySelector('.show-pwd img').src = route_origins + 'jcaptcha?' + Date.now()
                return msgPopUp(res)
            }
            if (res.code === 200 || res.code === -1) {
                if (isAborted && res.code === -1) return
                isAborted = false
                if (res.code === -1) {
                    Message({
                        message: res.msg || '接口服务错误！',
                        type: 'error',
                        duration: 3 * 1000
                    })
                    return
                }
                (res.module instanceof Object) && (res.module.code = res.code)
                return res.module || res.data || res
            } else {
                isAborted = false
                // console.error('code!=(200|-1|>100000):', res)
                // -100约定为登录出问题的情况：统一弹错误提示
                if (res.code === -100) {
                    return msgPopUp(res)
                }
                return res.data
            }
        }

        if (res.msg) {
            Message({
                message: res.msg,
                type: 'error',
                duration: 3 * 1000
            })
        }

        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
            MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // store.dispatch('FedLogOut').then(() => {
                //     // location.reload() // 为了重新实例化vue-router对象 避免bug
                // })
            })
        }
        return Promise.reject('error')
    },
    error => {
        console.log('err' + error) // for debug
        if (error.msg) {
            Message({
                // message: error.message,
                message: error.msg,
                type: 'error',
                duration: 3 * 1000
            })
        }
        return Promise.reject(error)
    }
)

service._origin = _origin

export default service